import xml.etree.ElementTree as ET

# 创建根元素
root = ET.Element("bookstore")

# 添加子元素  child = ET.Element(tag, attrib={}, **extra)
book1 = ET.Element('book', {'id': '001'})
title1 = ET.Element('title')
title1.text = 'Python for Beginners'
author1 = ET.Element('author')
author1.text = 'John Smith'
year1 = ET.Element('year')
year1.text = '2019'

book1.append(title1)
book1.append(author1)
book1.append(year1)

root.append(book1)

# 保存XML文件
tree = ET.ElementTree(root)
tree.write('books.xml', encoding='utf-8', xml_declaration=True)  # xml_declaration: XML声明，如果不需要写入，则 False

